package com.mbc.common.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mbc.common.entities.UserInRoles;

public class UserInRolesDAOImpls extends DAO<UserInRoles> implements UserInRolesDAO {

	public UserInRolesDAOImpls(Connection conn)
	{
		this.conn = conn;
		this.table_name = "UserInRoles";
	}

	@Override
	public void create(UserInRoles entity) throws SQLException {
		query = "insert into " + table_name + " ( roleid, userid) values( ?, ?)";
		pstmt = conn.prepareStatement(query);
		int i = 1;
		pstmt.setLong(i++, entity.getRoleId());
		pstmt.setLong(i++, entity.getUserId());

		pstmt.executeUpdate();
		pstmt.close();
	}

	@Override
	protected UserInRoles readRecord(ResultSet rs) throws SQLException {
		UserInRoles l_entity = new UserInRoles();
		l_entity.setAutoKey(rs.getLong("autokey"));
		l_entity.setRoleId(rs.getLong("roleid"));
		l_entity.setUserId(rs.getLong("userid"));

		return l_entity;
	}

	@Override
	public void deleteByUserId(long userId) throws SQLException {
		query = getDeleteQuery() + " where userid = " + userId;
		pstmt = conn.prepareStatement(query);
		pstmt.executeUpdate();
		pstmt.close();
	}

	@Override
	public ArrayList<UserInRoles> findByUserId(long userId) throws SQLException {
		ArrayList<UserInRoles> l_UsersInRolesList = new ArrayList<UserInRoles>();
		query = getSelectQuery() + " where userid = " + userId;
		pstmt = conn.prepareStatement(query);
		rs = pstmt.executeQuery();
		while (rs.next()) {
			l_UsersInRolesList.add(readRecord(rs));
		}
		rs.close();
		pstmt.close();
		return l_UsersInRolesList;
	}
}
